<?php
set_include_path($_SERVER['DOCUMENT_ROOT']);
include_once 'admin/includes/functions/admin-functions.php';
ini_set('display_errors',1);
ini_set('error_reporting',E_ALL ^ E_NOTICE ^ E_WARNING);
global  $CONFIG,$SMARTY,$DBobject;

echo "=> Cron started<br>";
$classTermObj = new ClassTermClass();
$enrol_obj = new Enrolment();

$devAdmin = "readysteadygokids@bccgmail.com";
$from = (string) $CONFIG->company->name;
$fromEmail = 'noreply@'. str_replace('www.', '', $GLOBALS['HTTP_HOST']);
$COMP = json_encode($CONFIG->company);
$SMARTY->assign('COMPANY', json_decode($COMP,TRUE));
$SMARTY->assign('DOMAIN', "http://" . $GLOBALS['HTTP_HOST']);

$events = array();
$membersEmailArr = array();

$subject = "澳睿跑 (Ready Steady Go Kids) | 付款提醒";
$day = date('Y-m-d');

//Only at THEM
if($_SERVER['REMOTE_ADDR']=='150.101.230.130' && !empty($_REQUEST['date'])){
	$day = date('Y-m-d', strtotime($_REQUEST['date']));
}

echo "=> Partial Payment Reminder:  $day  <br>";


//Get "Partial payment reminder" message
$sql = "SELECT email_additional_content FROM tbl_email_additional WHERE email_additional_deleted IS NULL AND email_additional_id = '20' "; 
$res = $DBobject->wrappedSql($sql);
$email_content = unclean($res[0]['email_additional_content']);

if(empty($email_content)) $events['error'][] = "Content message in '$subject' is null. ";

try {
	// Get current terms
	$sql = "SELECT user_id, user_gname, user_surname, user_email, debt_amount, debt_nextpayment_date, payment_transaction_no, payment_created
		FROM tbl_debt 
			LEFT JOIN tbl_payment ON payment_id = debt_payment_id
			LEFT JOIN tbl_user ON user_id = payment_user_id 
		WHERE debt_deleted IS NULL AND debt_paid_date IS NULL AND user_deleted IS NULL AND payment_deleted IS NULL AND debt_nextpayment_date = :date
		";
	$params = array (":date"=>$day);
	if($payments = $DBobject->wrappedSql($sql, $params)){
		foreach($payments as $e){
			$membersEmailArr[] = $e['user_email'];
			$SMARTY->assign('data', $e);
			$SMARTY->assign('content', $email_content);
			$body = $SMARTY->fetch('cron/email-partialpayment.tpl');
			die($body);
			//createBulkMail(array($e['user_email']), $from, $fromEmail, $subject, $body, 0, array($e['user_id']));
		}
	} 
	$events['records']['email'] = $membersEmailArr;
	
} catch (Exception $e) {
	$events['error'][] = "Error while running".$e;
}

//createBulkMail(array($devAdmin), $from, $fromEmail, "CRON JOB - PAYMENT REMINDER $day", json_encode($events));
echo "<br>=> Cron ended";

